<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="baidu-site-verification" content="4OYpSWALtb">
<meta name="theme-color" content="#222">
<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>

<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/zxmLogo.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/zxmLogo.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/zxmLogo.png?v=5.1.4">






  <meta name="keywords" content="webpack,">










<meta name="description" content="写在前面这是webpack实战系列的第二篇：模块和模块打包。上一篇：webpack实战——打包第一个应用 记录了webpack的一些基础内容与一个简单地小例子，开启了webpack的实战之路，这一篇记录一下关于模块和模块打包。">
<meta name="keywords" content="webpack">
<meta property="og:type" content="article">
<meta property="og:title" content="webpack实战——模块打包">
<meta property="og:url" content="https://flowing_eyes.gitee.io/flowing_eyes.gitee.io/2020/07/06/webpack实战——模块打包/index.html">
<meta property="og:site_name" content="Lomo | 朱幸民">
<meta property="og:description" content="写在前面这是webpack实战系列的第二篇：模块和模块打包。上一篇：webpack实战——打包第一个应用 记录了webpack的一些基础内容与一个简单地小例子，开启了webpack的实战之路，这一篇记录一下关于模块和模块打包。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://flowing_eyes.gitee.io/images/posts/webpack2-1.png">
<meta property="og:updated_time" content="2020-07-07T09:00:47.546Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="webpack实战——模块打包">
<meta name="twitter:description" content="写在前面这是webpack实战系列的第二篇：模块和模块打包。上一篇：webpack实战——打包第一个应用 记录了webpack的一些基础内容与一个简单地小例子，开启了webpack的实战之路，这一篇记录一下关于模块和模块打包。">
<meta name="twitter:image" content="https://flowing_eyes.gitee.io/images/posts/webpack2-1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://flowing_eyes.gitee.io/flowing_eyes.gitee.io/2020/07/06/webpack实战——模块打包/">





  <title>webpack实战——模块打包 | Lomo | 朱幸民</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Lomo | 朱幸民</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">on the way</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-主页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            主页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-标签">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-分类">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-时间轴">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            时间轴
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-categories" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://flowing_eyes.gitee.io/flowing_eyes.gitee.io/2020/07/06/webpack实战——模块打包/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Lomo 朱幸民">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/headImg.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Lomo | 朱幸民">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">webpack实战——模块打包</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-06T16:40:17+08:00">
                2020-07-06
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2020-07-07T17:00:47+08:00">
                2020-07-07
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/前端笔记/" itemprop="url" rel="index">
                    <span itemprop="name">前端笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2020/07/06/webpack实战——模块打包/" class="leancloud_visitors" data-flag-title="webpack实战——模块打包">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3k字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="写在前面"><a href="#写在前面" class="headerlink" title="写在前面"></a>写在前面</h2><p>这是<strong>webpack实战</strong>系列的第二篇：<strong>模块和模块打包</strong>。上一篇：<strong>webpack实战——打包第一个应用</strong> 记录了webpack的一些基础内容与一个简单地小例子，开启了webpack的实战之路，这一篇记录一下关于模块和模块打包。</p>
<a id="more"></a>
<h2 id="模块"><a href="#模块" class="headerlink" title="模块"></a>模块</h2><p>先看一下模块的定义：</p>
<blockquote>
<p>模块,是能够单独命名并独立地完成一定功能的程序语句的集合（即程序代码和数据结构的集合体）。它具有两个基本的特征：外部特征和内部特征。外部特征是指模块跟外部环境联系的接口（即其他模块或程序调用该模块的方式，包括有输入输出参数、引用的全局变量）和模块的功能；内部特征是指模块的内部环境具有的特点（即该模块的局部数据和程序代码）。</p>
</blockquote>
<p>可以从定义中看出，每个独立的模块负责不同工作，彼此之间又可以联系在一起共同保证整体系统运行。那么在webpack中，如何将其打包成一个（或多个）文件呢？</p>
<p>想了解这些，我们还是先要熟悉在 Javascript 中的模块。在 Javascript 模块化中比较常见的有：</p>
<ul>
<li>CommonJS</li>
<li>ES6 module</li>
<li>AMD</li>
<li>CMD</li>
<li>UMD(AMD和CommonJS)</li>
<li>…</li>
</ul>
<p>但由于在目前的使用场景中 <code>CommonJS</code> 和 <code>ES6 module</code> 居多，因此暂时就这两者进行讨论。</p>
<h2 id="1-CommonJS"><a href="#1-CommonJS" class="headerlink" title="1. CommonJS"></a>1. CommonJS</h2><h3 id="1-1-模块"><a href="#1-1-模块" class="headerlink" title="1.1 模块"></a>1.1 模块</h3><p><strong>在 CommonJS 中规定每个文件都是一个模块。</strong></p>
<p>在 CommonJS 中，变量及函数的声明不会造成全局污染。如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="keyword">var</span> name = <span class="string">'name: add.js'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">var</span> name = <span class="string">'name: index.js'</span>;</span><br><span class="line">reuqire(<span class="string">'./add.js'</span>);</span><br><span class="line"><span class="built_in">console</span>.log(name);  <span class="comment">// name: index.js</span></span><br></pre></td></tr></table></figure>
<p>在上面 index.js 中通过 require 函数来加载 add.js ，输出的结果是 <code>name: index.js</code> ，说明在 add 中定义的变量并不会影响 index ，可以得出使用 CommonJs 模块，作用域只针对于该模块，而<strong>不会造成全局污染，对外不可见</strong>。</p>
<h3 id="1-2-导出"><a href="#1-2-导出" class="headerlink" title="1.2 导出"></a>1.2 导出</h3><p>前面说过模块拥有自己的作用域，那么模块是需要向外传递的，怎么办呢？<br><strong>导出是一个模块向外暴露自身的唯一方式</strong>。在 CommonJS 中，我们通过 <code>module.exports</code> 来导出模块中的内容。如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    name: <span class="string">'add'</span>,</span><br><span class="line">    add: <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a + b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 CommonJS 内部会有一个 module 对象用于存放当前模块的信息。而 module.exports 则指定向外暴露的内容。</p>
<h3 id="1-3-导入"><a href="#1-3-导入" class="headerlink" title="1.3 导入"></a>1.3 导入</h3><p>导出自然是为了另外一个模块来使用，这时便使用到了导入功能。在 CommonJS 中，使用 require 来进行模块导入：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    name: <span class="string">'add'</span>,</span><br><span class="line">    add: <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a + b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">const</span> add = <span class="built_in">require</span>(<span class="string">'./add.js'</span>);</span><br><span class="line"><span class="keyword">const</span> sum = add.add(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(sum);   <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>
<p>上面这个例子，便是在 index.js 中通过 require 导入了 add.js ，并且调用了其中的 add() 方法。</p>
<p>而我们在 reuqire 一个模块的时候，会分两种情况：</p>
<ol>
<li>如果 require 的模块第一次被加载，那么会执行该模块然后导出内容；</li>
<li>如果非首次加载，那么该模块代码不会再次执行，而是直接导出上次代码执行后所得到的结果。</li>
</ol>
<p>有时候我们只想通过加载执行某个模块让它产生某种作用而不需要获取它所导出的内容，则可以直接通过 require 来导入而不需要定义：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">require</span>(<span class="string">'./task.js'</span>);</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>而通过这个特性，加上 require 函数可以接收表达式，那么我们则可以动态指定模块加载路径：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> moduleList = [<span class="string">'add.js'</span>, <span class="string">'subtract.js'</span>];</span><br><span class="line">moduleList.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">require</span>(<span class="string">`./<span class="subst">$&#123;item&#125;</span>`</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="2-ES6-Module"><a href="#2-ES6-Module" class="headerlink" title="2. ES6 Module"></a>2. ES6 Module</h2><p>熟悉 JavaScript 语言的小伙伴知道，其实在 JavaScript 设计之初，并没有模块化这个概念。而伴随 JavaScript 不断的壮大发展，社区中也涌现出了不少模块化概念。一直到 ES6 ， JavaScript 终于正式的有了模块化这一特性。</p>
<h3 id="2-1-模块"><a href="#2-1-模块" class="headerlink" title="2.1 模块"></a>2.1 模块</h3><p>在前面我们使用 CommonJS 实现了一个例子来展示 CommonJS 的模块、导出与导入，同样在此处也先来一个例子，只需将上面例子稍微改写即可：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    name: <span class="string">'add'</span>,</span><br><span class="line">    add: <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a + b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">import</span> add <span class="keyword">from</span> <span class="string">'./add.js'</span>;</span><br><span class="line"><span class="keyword">const</span> sum = add.add(<span class="number">-1</span>, <span class="number">1</span>);</span><br><span class="line"><span class="built_in">console</span>.log(sum);   <span class="comment">// 0</span></span><br></pre></td></tr></table></figure>
<p>ES6 Module 也是将每一个文件都作为一个模块，并且每个模块拥有自身的作用域，但是与 CommonJS 相比， 不同的是导入、导出语句。在 ES6 Module 中，<br>import 和 export 也作为关键字被保留。</p>
<h3 id="2-2-导出"><a href="#2-2-导出" class="headerlink" title="2.2 导出"></a>2.2 导出</h3><p>在 ES6 Module 中，使用 export 来对模块进行导出。</p>
<p>export 导出的两种方式：</p>
<ul>
<li>命名导出</li>
<li>默认导出</li>
</ul>
<h4 id="2-2-1-命名导出"><a href="#2-2-1-命名导出" class="headerlink" title="2.2.1 命名导出"></a>2.2.1 命名导出</h4><p>以下有两种写法，但其效果并无区别：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 命名导出： 两种写法</span></span><br><span class="line"><span class="comment">**/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1. 声明和导出写在一起</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> name = <span class="string">'add'</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> add = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2. 先声明，再统一导出</span></span><br><span class="line"><span class="keyword">const</span> name = <span class="string">'add'</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> &#123; name, add &#125;</span><br></pre></td></tr></table></figure>
<p><strong>as关键字</strong></p>
<p>在使用命名导出时，如果用写法2（先声明再统一导出），可以使用 <code>as 关键字</code> 来对导出的变量进行重命名。如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> name = <span class="string">'add'</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// add as sum ： 在导入时，使用 name 和 sum 即可</span></span><br><span class="line"><span class="keyword">export</span> &#123; name, add <span class="keyword">as</span> sum &#125;</span><br></pre></td></tr></table></figure>
<h4 id="2-2-2-默认导出"><a href="#2-2-2-默认导出" class="headerlink" title="2.2.2 默认导出"></a>2.2.2 默认导出</h4><p>说完了命名导出，来到默认导出：模块的默认导出只能导出一个。举例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 默认导出</span></span><br><span class="line"><span class="keyword">export</span> defailt &#123;</span><br><span class="line">    name: <span class="string">'add'</span>,</span><br><span class="line">    add: <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a + b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由上可见，我们可以将默认导出理解为向外输出了一个命名为 default 的变量。</p>
<h3 id="2-3-导入"><a href="#2-3-导入" class="headerlink" title="2.3 导入"></a>2.3 导入</h3><p>ES6 Module 中使用 import 进行模块导入。由于在 ES6 Module 的导出中，分为 <code>命名导出</code> 和 <code>默认导出</code> ，因此在导入的时候也有对应的两种方式进行导入。</p>
<h4 id="2-3-1-命名"><a href="#2-3-1-命名" class="headerlink" title="2.3.1 命名"></a>2.3.1 命名</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="keyword">const</span> name = <span class="string">'add'</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> &#123; name, add &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">import</span> &#123; name, add &#125; <span class="keyword">from</span> <span class="string">'./add.js'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(name, add(<span class="number">1</span>, <span class="number">2</span>));   <span class="comment">// add 3</span></span><br></pre></td></tr></table></figure>
<p>可以看到，在使用 import 对命名导出模块进行引入的时候， import 后面跟了一对花括号 <code>{ }</code> 将导入的变量名包裹起来，并且变量名需要与导出时的变量命名一样。同样，我们还是可以使用 <code>as 关键字</code> 来对变量进行重命名：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">import</span> &#123; name, add <span class="keyword">as</span> sum &#125; <span class="keyword">from</span> <span class="string">'./add.js'</span></span><br><span class="line">sum(<span class="number">2</span>, <span class="number">2</span>);  <span class="comment">// 4</span></span><br></pre></td></tr></table></figure>
<p><strong><em>值得注意的是，导入变量的效果相当于在当前作用域下声明了变量（如 name 和 add），但不可对这些变量不能修改，只可当成只读的来使用。</em></strong></p>
<p>当然，我们还可以使用 <code>*</code> 来进行整体导入：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> add <span class="keyword">from</span> <span class="string">'./add.js'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(add.name);  <span class="comment">// add</span></span><br><span class="line"><span class="built_in">console</span>.log(add.add(<span class="number">1</span>, <span class="number">1</span>)); <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<h4 id="2-3-2-默认"><a href="#2-3-2-默认" class="headerlink" title="2.3.2 默认"></a>2.3.2 默认</h4><p>对于默认导出的导入处理如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    name: <span class="string">'add'</span>,</span><br><span class="line">    add: <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a + b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">import</span> addMe <span class="keyword">from</span> <span class="string">'./add.js'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(addMe.name, addMe.add(<span class="number">2</span>, <span class="number">5</span>));   <span class="comment">// add 7</span></span><br></pre></td></tr></table></figure>
<p>可以看到，如果是导入默认导出的模块，那么在 import 后面直接跟变量名即可，并且这个变量名无需与导出模块的变量名重复，可以自己指定新的变量名。</p>
<h2 id="3-CommonJS-与-ES6-Module-的区别"><a href="#3-CommonJS-与-ES6-Module-的区别" class="headerlink" title="3. CommonJS 与 ES6 Module 的区别"></a>3. CommonJS 与 ES6 Module 的区别</h2><p>介绍了 CommonJS 与 ES6 Module 的基础应用之后，我们也要了解到在实际的开发过程中我们经常将这两者在同一个项目中混用。为了避免不必要的麻烦，还是要说一下两者的异同。</p>
<h3 id="3-1-动态与静态"><a href="#3-1-动态与静态" class="headerlink" title="3.1 动态与静态"></a>3.1 动态与静态</h3><p><strong>CommonJS 对模块依赖的解决是动态的，而 ES6 Module 对模块依赖的解决是静态的。</strong></p>
<p>首先要了解这里说的<code>动态</code>与<code>静态</code>是什么：</p>
<ul>
<li>动态： 模块依赖关系的建立发生在代码<code>运行阶段</code>；</li>
<li>静态： 模块依赖关系的建立发生在代码<code>编译阶段</code>；</li>
</ul>
<p>由于 ES6 Module 中导入导出语句都是声明式的，不支持导入表达式类路径，并且导入导出语句必须位于模块的顶层作用域。相比 CommonJS ，具备优势如下：</p>
<ul>
<li><strong>死代码检测和排除</strong>： 可以使用静态分析工具检测出没有被调用的模块，减小打包资源体积；</li>
<li><strong>模块变量类型检查</strong>： 有助于确保模块之间传递的值或者接口类型的正确性；</li>
<li><strong>编译器优化</strong>： ES6 Module 直接导入变量，减少层级引用，程序效率更高。</li>
</ul>
<h3 id="3-2-值拷贝和动态映射"><a href="#3-2-值拷贝和动态映射" class="headerlink" title="3.2 值拷贝和动态映射"></a>3.2 值拷贝和动态映射</h3><p>在导入一个模块时，对于 CommonJS 来说获取的是一份导出值的拷贝，而在 ES6 Module 中则是值的动态映射，这个映射是只读的。例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="keyword">var</span> count = <span class="number">0</span>;</span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    count: count,</span><br><span class="line">    add: <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">        count += <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">return</span> a + b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">var</span> count = <span class="built_in">require</span>(<span class="string">'./add.js'</span>).count;</span><br><span class="line"><span class="keyword">var</span> add = <span class="built_in">require</span>(<span class="string">'./add/js'</span>).add;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(count); <span class="comment">// 0 (这里的count是对add.js中couunt的拷贝)</span></span><br><span class="line">add(<span class="number">2</span>, <span class="number">3</span>);</span><br><span class="line"><span class="built_in">console</span>.log(count); <span class="comment">// 0 (add.js中变量值的改变不会对这里的拷贝值造成影响)</span></span><br><span class="line"></span><br><span class="line">count += <span class="number">1</span>;</span><br><span class="line"><span class="built_in">console</span>.log(count); <span class="comment">// 1 (拷贝的值 0 + 1 = 1，表示拷贝的值可以更改)</span></span><br></pre></td></tr></table></figure>
<p>可以看出，index.js 中的 count 是 add.js 中 count 的一份值拷贝，因此在调用 add 函数时，即便更改了 add 中的 count，但不会对 index.js 中的值拷贝造成影响。</p>
<p>但在 ES6 Module 中，却不一样：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="keyword">let</span> count = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    count += <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">export</span> &#123; count, add &#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">import</span> &#123; count, add &#125; <span class="keyword">from</span> <span class="string">'./add.js'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(count); <span class="comment">// 0 (对add.js中count值的映射)</span></span><br><span class="line">add(<span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line"><span class="built_in">console</span>.log(count); <span class="comment">// 1 (对add.js中count值的映射，会映射值的变化)</span></span><br><span class="line"></span><br><span class="line">count += <span class="number">1</span>; <span class="comment">// 报错，该count值不可更改</span></span><br></pre></td></tr></table></figure>
<h2 id="4-模块打包原理"><a href="#4-模块打包原理" class="headerlink" title="4. 模块打包原理"></a>4. 模块打包原理</h2><p>前面描述了一些基础的 CommonJS 与 ES6 Module 模块化的一些知识，那么回到 webpack 中来：webpack是如何将各种模块有序的组织在一起的呢？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add.js</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    add: <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a + b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index.js</span></span><br><span class="line"><span class="keyword">const</span> add = <span class="built_in">require</span>(<span class="string">'./add.js'</span>);</span><br><span class="line"><span class="keyword">const</span> sum = add(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">`sum: <span class="subst">$&#123;sum&#125;</span>`</span>);</span><br></pre></td></tr></table></figure>
<p>还是之前的例子，但现在经过 webpack 打包之后，它会变成什么样子呢？</p>
<p><img src="/images/posts/webpack2-1.png" alt="bundle.js"></p>
<p>如图所示，这便是一个简单地打包结果。我们可以观察自己的 bundle.js 文件，从中看打包逻辑关系：</p>
<ul>
<li>首先一个立即执行匿名函数，包裹所有内容，构成资深作用域；</li>
<li>installedModule对象（模块缓存），每个模块在第一次被加载的时候执行，到处结果存储到其中，以后再次调用模块直接取值即可，不会再次执行模块；</li>
<li><strong>webpack_require</strong>函数： 对模块加载的实现，在浏览器中可以通过调用此函数加模块id来进行模块导入；</li>
<li>modules对象：工程中所有产生依赖关系的模块都会以 <code>key-value</code> 形式放在此对象中， key 作为模块 id，由数字或者 hash 字符串构成，value 则由一个匿名函数包裹的模块构成，匿名函数的参数则赋予了每个模块导出和导入能力。</li>
</ul>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>本篇记录了关于 JavaScript 的模块化与 webpack 的模块打包原理简介。</p>
<p>首先，介绍了关于模块的概念，然后依次介绍了两种模块化：CommonJS 和 ES6 Module ，以及他们分别的模块概念、导出和导入，接着介绍了他们之间的两个差异：动态与静态、值拷贝和映射。最后，提及了一下模块化打包的简单原理，对webpack打包工作有一个大概认知。</p>
<p>下一篇将会介绍在webpack中资源的输入与输出。敬请期待。</p>
<hr>
<p>学习推荐： 本系列学习资源多来自于 <em>《webpack实战 入门、进阶与调优》</em> ，作者 <em>居玉皓</em> ， 感兴趣的朋友可以购买实体书支持学习~</p>

      
    </div>
    
    
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">---本文结束<i class="fa fa-paw"></i>感谢您的阅读---</div>
    
</div>
	  
	</div>
	<div>
		  
			
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script src="https://ituac-blog-1252741530.cos.ap-beijing.myqcloud.com/zxm/github/sweetalert.main.js"></script>
  <link rel="stylesheet" type="text/css" href="https://ituac-blog-1252741530.cos.ap-beijing.myqcloud.com/zxm/github/sweetalert.css">

  <p><span>本文标题:</span>webpack实战——模块打包</p>
  <p><span>文章作者:</span>Lomo 朱幸民</p>
  <p><span>发布时间:</span>2020年07月06日 - 16:40:17</p>
  <p><span>最后更新:</span>2020年07月07日 - 17:00:47</p>
  <p><span>原始链接:</span><a href="/2020/07/06/webpack实战——模块打包/" title="webpack实战——模块打包">https://flowing_eyes.gitee.io/flowing_eyes.gitee.io/2020/07/06/webpack实战——模块打包/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://flowing_eyes.gitee.io/flowing_eyes.gitee.io/2020/07/06/webpack实战——模块打包/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    clipboard.on('success', $(function(){
      $(".fa-clipboard").click(function(){
        swal({   
          title: "",   
          text: '复制成功',   
          html: false,
          timer: 500,   
          showConfirmButton: false
        });
      });
    }));  
</script>

		  
	</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>请作者喝杯咖啡吧~</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Lomo 朱幸民 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Lomo 朱幸民 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/webpack/" rel="tag"><i class="fa fa-tag"></i> webpack</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/03/webpack实战——打包第一个应用/" rel="next" title="webpack实战——打包第一个应用">
                <i class="fa fa-chevron-left"></i> webpack实战——打包第一个应用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/07/13/webpack实战——资源输入与输出/" rel="prev" title="webpack实战——资源输入与输出">
                webpack实战——资源输入与输出 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
	
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/headImg.png" alt="Lomo 朱幸民">
            
              <p class="site-author-name" itemprop="name">Lomo 朱幸民</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">100</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">91</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          <!--
		  */
		  -->



          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xuan0146" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:zxm0146@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/a708dcdb5061" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-book"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/5094024813" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
            </div>
          

          
          

          
          

		  <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="298" height="52" src="//music.163.com/outchain/player?type=2&id=756112&auto=1&height=32"></iframe>
		  

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#写在前面"><span class="nav-text">写在前面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模块"><span class="nav-text">模块</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-CommonJS"><span class="nav-text">1. CommonJS</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-模块"><span class="nav-text">1.1 模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-导出"><span class="nav-text">1.2 导出</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-导入"><span class="nav-text">1.3 导入</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-ES6-Module"><span class="nav-text">2. ES6 Module</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-模块"><span class="nav-text">2.1 模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-导出"><span class="nav-text">2.2 导出</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-1-命名导出"><span class="nav-text">2.2.1 命名导出</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-2-默认导出"><span class="nav-text">2.2.2 默认导出</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-导入"><span class="nav-text">2.3 导入</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-1-命名"><span class="nav-text">2.3.1 命名</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-2-默认"><span class="nav-text">2.3.2 默认</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-CommonJS-与-ES6-Module-的区别"><span class="nav-text">3. CommonJS 与 ES6 Module 的区别</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-动态与静态"><span class="nav-text">3.1 动态与静态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-值拷贝和动态映射"><span class="nav-text">3.2 值拷贝和动态映射</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-模块打包原理"><span class="nav-text">4. 模块打包原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小结"><span class="nav-text">小结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      


    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Lomo 朱幸民</span>

  
</div>








<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共116k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("ivrWycPPaTqpUQWlrrynaC9b-gzGzoHsz", "hEXywpn5sGaCnm5zWsMmEu2j");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
